<template>
  <page-header-wrapper>
    <a-card :bordered="false" style="margin-bottom: 11px" v-if="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="20">
            <a-col :md="8" :sm="24">
              <a-form-item label="角色ID">
                <a-input placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select placeholder="请选择" default-value="-1">
                  <a-select-option value="-1">全部</a-select-option>
                  <a-select-option value="1">启用</a-select-option>
                  <a-select-option value="0">禁用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary">查询</a-button>
                <a-button style="margin-left: 8px">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="card_style_re">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <span></span>
        <a-button type="primary" @click="onAdd" icon="plus">新建</a-button>
      </div>
      <s-table row-key="id" size="default" :columns="columns" :data="loadData" ref="table">
        <span slot="role" slot-scope="text, record">
          <a-tag color="blue" v-for="(item, index) of record.roles" :key="index">
            {{ item.name }}
          </a-tag>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-popconfirm
            :disabled="record.username == 'admin'"
            title="确认删除该账号吗？"
            @confirm="handleDelete(record)"
          >
            <a-button type="link" size="small">删除</a-button>
          </a-popconfirm>
        </span>
      </s-table>

      <a-modal
        :title="isNew ? '创建账号' : '编辑账号'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        v-model="visible"
        @ok="handleOk"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="用户名" hasFeedback>
            <a-input
              placeholder="用户名"
              :disabled="records.username && records.username == 'admin'"
              v-decorator="['username', { rules: [{ required: true, message: '请填写用户名' }] }]"
            />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="邮箱" hasFeedback>
            <a-input
              placeholder="邮箱"
              v-decorator="['email', { rules: [{ type: 'email', message: '请填写正确的邮箱' }] }]"
            />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="昵称" hasFeedback>
            <a-input
              placeholder="昵称"
              v-decorator="['name', { rules: [{ required: true, message: '请填写昵称' }] }]"
            />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="手机号" hasFeedback>
            <a-input
              placeholder="手机号"
              v-decorator="['mobile', { rules: [{ pattern: /^[1]([3-9])[0-9]{9}$/, message: '请填写正确的手机号' }] }]"
            />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="密码" hasFeedback>
            <a-input
              :placeholder="isNew ? '密码' : '不修改请留空'"
              v-decorator="['password', { rules: [{ required: isNew, message: '请填写密码' }] }]"
            />
          </a-form-item>

          <a-form-item v-if="records.username != 'admin'" :labelCol="labelCol" :wrapperCol="wrapperCol" label="角色">
            <a-select
              mode="multiple"
              size="default"
              placeholder="请选择角色"
              :default-value="selectedRole"
              @change="handleChange"
            >
              <a-select-option :value="item.id" v-for="(item, index) of roleList" :key="index">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注" hasFeedback>
            <a-textarea :rows="2" id="remark" v-decorator="['remark']" />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import pick from 'lodash.pick'
import { STable } from '@/components'
import {
  getAdminList,
  createAdmin,
  editAdmin,
  deleteAdmin,
  saaSgetAdminList,
  saaScreateAdmin,
  saaSeditAdmin,
  saaSdeleteAdmin,
} from '@/api/auth'

const columns = [
  {
    title: '账号',
    dataIndex: 'username',
  },
  {
    title: '昵称',
    dataIndex: 'name',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
  },
  {
    title: '角色',
    scopedSlots: { customRender: 'role' },
  },
  {
    title: '备注',
    dataIndex: 'remark',
  },
  {
    title: '创建日期',
    dataIndex: 'created_at',
  },
  {
    title: '操作',
    width: '150px',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'AdminList',
  components: {
    STable,
  },
  data() {
    return {
      isNew: false,
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      form: this.$form.createForm(this),
      // 表头
      columns,
      modalLoading: false,
      // 角色列表
      roleList: [],
      // 选择的角色
      selectedRole: [],
      records: {},
      type: 1,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        if (this.type === 0) {
          return saaSgetAdminList(parameter).then((res) => {
            console.log('getRoleList', res)
            this.roleList = res.data.roles
            return res.data
          })
        }

        return getAdminList(parameter).then((res) => {
          this.roleList = res.data.roles
          return res.data
        })
      },
    }
  },
  created() {
    let { type } = this.$route.meta
    this.type = type
  },
  methods: {
    handleEdit(record) {
      this.isNew = false
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, ['username', 'email', 'name', 'mobile', 'remark']))
      })
      const roles = []
      for (let i = 0; i < record.roles.length; i++) {
        roles.push(record.roles[i].id + '')
      }
      this.selectedRole = roles
      this.records = record
    },

    submitCallBack(res, msg = '账号编辑成功！') {
      this.modalLoading = false
      if (res.code !== 0) {
        this.$error({
          content: res.msg,
        })
      } else {
        this.$message.success(msg)
        this.visible = false
        this.$refs.table.refresh()
      }
    },

    handleOk(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          return false
        }
        values.roles = this.selectedRole
        this.modalLoading = true
        if (this.isNew) {
          if (this.type === 0) {
            saaScreateAdmin(values).then((res) => {
              this.submitCallBack(res, '账号创建成功！')
            })
            return
          }

          createAdmin(values).then((res) => {
            this.submitCallBack(res, '账号创建成功！')
          })
        } else {
          values.id = this.records.id

          if (this.type === 0) {
            saaSeditAdmin(values).then((res) => {
              this.submitCallBack(res)
            })
            return;
          }

          editAdmin(values).then((res) => {
            this.submitCallBack(res)
          })
        }
      })
    },
    onAdd: function () {
      this.isNew = true
      this.visible = true
      this.records = {}
      this.selectedRole = []
    },
    handleDelete: function (record) {
      const hide = this.$message.loading('删除中...', 0)

      deleteAdmin({
        id: record.id,
      }).then((res) => {
        hide()
        if (res.code === 0) {
          this.$message.success('账号删除成功！')
          this.$refs.table.refresh()
        } else {
          this.$error({
            content: res.msg,
          })
        }
      })
    },
    handleChange: function (value) {
      console.log(value)
      this.selectedRole = value
    },
  },
}
</script>

<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
</style>
